<template>
  <!-- 微信支付 -->
    <van-cell-group inset>
      <!-- 允许输入数字，调起带符号的纯数字键盘 -->
      <van-field v-model="amount" type="number" label="金 额" placeholder="请输入金额" />
    </van-cell-group>
    <van-space direction="vertical" fill style="margin: 0 10px;">
      <van-button size="small" type="success" @click="wechatPayUse" block>微信支付</van-button>
    </van-space>

    <van-divider content-position="left">支付结果</van-divider>

    <van-search v-model="search" placeholder="请输入订单号" @search="getPayList()" />
    <van-list
      finished-text="没有更多了">
      <van-cell v-for="item in orderList" :key="item" >
        <div class="list-item">
          <div class="order-no">
            <van-tag :type="item.tradeState === 'SUCCESS' ? 'success' : 'primary'">{{ item.tradeState }}</van-tag>
            <p>商户订单号：{{ item.orderNo }}</p>
            <p>微信支付单号：{{ item.transactionId }}</p>
            <p>交易时间：{{ item.createAt }}</p>
          </div>
          <div class="amount">
            <p>订单金额：<span >{{ moneyFormat(item.amount / 100) }}</span></p>
            <p>&nbsp;</p>
            <van-tag type="info">{{ item.tradeType }}</van-tag>
          </div>
        </div>
      </van-cell>
    </van-list>
    <van-divider></van-divider>
    <van-pagination v-model="page" :page-count="total / limit" mode="simple" />
</template>

<script setup>
import { onMounted, ref } from 'vue'
import axios from 'axios'
import { showNotify } from 'vant';

onMounted(() => {
  getPayList()
  // if (typeof WeixinJSBridge == "undefined") {
  //   if (document.addEventListener) {
  //     document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
  //   } else if (document.attachEvent) {
  //     document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
  //     document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
  //   } else {
  //     console.log('weixin js bridge not ready');
  //   }
  // } else {
  //   console.log('JS-SDK ready ~~~');
  // }
})

const props = defineProps({
  openid: {
    type: String,
    default: ''
  }
})

const amount = ref(0.1)

// 调用微信 jssdk，实现支付接口
const wechatPayUse = async () => {

  const { data } = await await axios.post('/wechat/payOrder', {
    description: '测试1元商品描述',
    notifyUrl: 'http://h5.cyberfuture.top/wechat/payNotify/',
    amount: Number(amount.value) * 100, // 单位为分
    openid: props.openid
  }); //获取参数
  console.log("🚀 ~ wechatPayUse ~ data:", data)

  if (data && data.code === 0) {
    const { appId, timeStamp, nonceStr, signType, paySign } = data.data;
    WeixinJSBridge.invoke('getBrandWCPayRequest', {
      "appId": appId,
      "timeStamp": timeStamp,
      "nonceStr": nonceStr,
      "package": data.data.package,
      "signType": signType,
      "paySign": paySign
    }, (res) => {
      // 调用回调接口，处理支付结果
      console.log("🚀 ~ wechatPayUse ~ res:", res)
      //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
      switch (res.err_msg) {
        case "get_brand_wcpay_request:ok":
          console.log("🚀 ~ wechatPayUse ~ 支付成功");
          // 成功通知
          showNotify({ type: 'success', message: '支付成功' });
          getPayList()
          break;
        case "get_brand_wcpay_request:cancel":
          console.log("🚀 ~ wechatPayUse ~ 取消支付");
          // 成功通知
          showNotify({ type: 'primary', message: '支付取消' });
          break;
        case "get_brand_wcpay_request:fail":
          console.log("🚀 ~ wechatPayUse ~ 支付失败");
          showNotify({ type: 'danger', message: '支付失败' });
          break;
        default:
          console.log("🚀 ~ wechatPayUse ~ 支付失败");
          break;
      }
    })
  }
  
}

const moneyFormat = (num) => {
  return Number(+num || 0).toFixed(2).toString().replace(/^-?\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ','))
}

const orderList = ref([])
const page = ref(1)
const limit = ref(10)
const total = ref(0)
const search = ref('')
// 支付订单
const getPayList = async () => {
  const { data } = await await axios.get('/wechat/payOrderList', {
    params: {
      orderNo: search.value,
      page: Number(page.value),
      limit: Number(limit.value)
    }
  });
  if (data && data.code === 0) {
    orderList.value = data.data
    total.value = data.data.length
  }
}

</script>

<style scoped>
.list-item {
  display: flex;
  justify-content: space-between;
  .order-no {
    text-align: left;
    flex: 1;
    margin: 0 10px;
  }
  .amount {
    width: 120px;
    text-align: left;
  }
}
</style>